/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.yuhanginfo.modules.sys.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yuhanginfo.common.config.Global;
import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.common.utils.FileUtils;
import com.yuhanginfo.common.utils.StringUtils;
import com.yuhanginfo.modules.sys.entity.EnquiryGoods;
import com.yuhanginfo.modules.sys.entity.EnquiryGoodsReply;
import com.yuhanginfo.modules.sys.entity.Parts;
import com.yuhanginfo.modules.sys.entity.YongUser;
import com.yuhanginfo.modules.sys.service.EnquiryGoodsReplyService;
import com.yuhanginfo.modules.sys.service.EnquiryGoodsService;
import com.yuhanginfo.modules.sys.service.PartsService;
import com.yuhanginfo.modules.sys.service.YongUserService;
import com.yuhanginfo.modules.sys.utils.UserUtils;

/**
 * 询价管理Controller
 * @author yangs
 * @version 2017-11-23
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/enquiryGoods")
public class EnquiryGoodsController extends BaseController {

	private static final  Logger logger = LoggerFactory.getLogger(EnquiryGoodsController.class);
	@Autowired
	private EnquiryGoodsService enquiryGoodsService;
	@Autowired
	private EnquiryGoodsReplyService enquiryGoodsReplyService;
	@Autowired
	private PartsService partsService;
	@Autowired
	private YongUserService userService;
	
	private static final  String REDIRECT = "redirect:"+Global.getAdminPath()+"/sys/enquiryGoods/?repage";
	@ModelAttribute
	public EnquiryGoods get(@RequestParam(required=false) String id) {
		EnquiryGoods entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = enquiryGoodsService.get(id);
		}
		if (entity == null){
			entity = new EnquiryGoods();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:enquiryGoods:view")
	@RequestMapping(value = {"list", ""})
	public String list(EnquiryGoods enquiryGoods, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EnquiryGoods> page = enquiryGoodsService.findPage(new Page<EnquiryGoods>(request, response), enquiryGoods);
        List<EnquiryGoods> list=page.getList();
        for (EnquiryGoods enquiryGoods2 : list) {
			String[] qui=enquiryGoods2.getQuality().split(";");
			List<Object> lis=new ArrayList<>();
			for (int i = 0; i < qui.length; i++) {
				if(qui[i].length()>0){
					lis.add(qui[i]);
				}
			}
			enquiryGoods2.setQuitList(lis);
		}
        page.setList(list);
		model.addAttribute("page",page );
		model.addAttribute("startTime", enquiryGoods.getStartTime());
		model.addAttribute("endTime",enquiryGoods.getEndTime());
		return "modules/sys/order/enquiryGoodsList";
	}

	@RequiresPermissions("sys:enquiryGoods:view")
	@RequestMapping(value = "form")
	public String form(EnquiryGoods enquiryGoods, Model model) {
		model.addAttribute("enquiryGoods", enquiryGoods);
		return "modules/sys/enquiryGoodsForm";
	}

	@RequiresPermissions("sys:enquiryGoods:edit")
	@RequestMapping(value = "save")
	public String save(EnquiryGoods enquiryGoods, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, enquiryGoods)){
			return form(enquiryGoods, model);
		}
		enquiryGoodsService.save(enquiryGoods);
		addMessage(redirectAttributes, "保存询价管理成功");
		return REDIRECT;
	}
	
	@RequiresPermissions("sys:enquiryGoods:edit")
	@RequestMapping(value = "delete")
	public String delete(EnquiryGoods enquiryGoods, RedirectAttributes redirectAttributes) {
		enquiryGoodsService.delete(enquiryGoods);
		addMessage(redirectAttributes, "删除询价管理成功");
		return REDIRECT;
	}
    
	@RequiresPermissions("sys:enquiryGoods:view")
	@RequestMapping(value = "enquireyDetail")
	public String enquireyDetail(String code,Model model){
		List<EnquiryGoods> list=enquiryGoodsService.selectByEnquiryGoodsId(code);
		for (EnquiryGoods enquiryGoods : list) {
			String[] image=enquiryGoods.getPhoto().split(";");
			List<Object> list0=new ArrayList<>();
			for (int i = 0; i < image.length; i++) {
				if(image[i]!=null && image[i]!=""){
					list0.add(image[i]);
				}
			}
			enquiryGoods.setImages(list0);
		}
		EnquiryGoods enquiryGoods=list.get(0);
		String[] quit=enquiryGoods.getQuality().split(";");
		List<Object> lis=new ArrayList<>();
		 for (int i = 0; i < quit.length; i++) {
			if(quit[i].length()>0){
				lis.add(quit[i]);
			}
		}
		model.addAttribute("lis", lis);
		model.addAttribute("enquiryGoods", list.get(0));
		model.addAttribute("list", list);
		model.addAttribute("code", code);
		return "modules/sys/order/enquiryGoodsForm";
	}
	
	
	
	@ResponseBody
	@RequiresPermissions("sys:enquiryGoods:edit")
	@RequestMapping(value = "useData")
	public Map<String,Object> useData(String code){
		Map<String,Object> map=new HashMap<>();
		String codes=code.substring(0,code.indexOf(';'));
		String ids=code.substring(code.indexOf(';')+1,code.length());
		List<Parts> partList=partsService.setByCode(codes);
		EnquiryGoods enquiryGoods=enquiryGoodsService.get(ids);
		YongUser yongUser=userService.selectById(enquiryGoods.getUserId());
		if(yongUser!=null && "2".equals(yongUser.getUserType()) && !partList.isEmpty()){
			for (Parts parts : partList) {
				parts.setGoodsPrice(parts.getMemberPrice());;
			}
		}
		map.put("part", partList);
		map.put("ids", ids);
		return map;
	}
	
	
   //询价回复保存
	@RequiresPermissions("sys:enquiryGoods:edit")
	@RequestMapping(value = "saveEnquiry")
   public String saveEnquiry(@RequestParam("photos") MultipartFile[] photos,HttpServletRequest request) throws IOException{
		String[] cnName = request.getParameterValues("cnName");
		String[] partsCode = request.getParameterValues("partsCode");
		String[] venderName = request.getParameterValues("venderName");
		String[] money = request.getParameterValues("money");
		String[] ids = request.getParameterValues("ids");
		String code = request.getParameter("code");
		String[] receiveDate = request.getParameterValues("receiveDate");
		String[] rearks = request.getParameterValues("rearks");
		String[] images = request.getParameterValues("images");
	   List<EnquiryGoods> list=enquiryGoodsService.selectByEnquiryGoodsId(code);
	   String[] fileName=new String[partsCode.length];
	   Integer gs=0;
	   StringBuilder  buf=new StringBuilder();
		for (int i = 0; i < photos.length; i++) {
			if(photos[i].getSize()>0){
			FileUtils.saveSimpleNewImage(UserUtils.getUser().getId(), photos[i].getOriginalFilename(), photos[i].getInputStream());
			buf.append(FileUtils.saveSimpleNewImage(UserUtils.getUser().getId(), photos[i].getOriginalFilename(), photos[i].getInputStream())+";");
		 }else{	
			 fileName[gs]=buf.toString();
			 gs++;
			 buf=new StringBuilder();
		 }
		
		}
		Date da=new Date();
	    for (int i = 0; i < ids.length; i++) {
	    	try {
	    	EnquiryGoodsReply enquiryGoodsReply=new EnquiryGoodsReply();
	    	enquiryGoodsReply.setEnquiryGoodsId(Integer.parseInt(ids[i]));
	    	enquiryGoodsReply.setMoney(money[i]);
	    	enquiryGoodsReply.setGoodsName(cnName[i]);
	    	enquiryGoodsReply.setPartsCode(partsCode[i]);
	    	enquiryGoodsReply.setProducer(venderName[i]);
	    	enquiryGoodsReply.setCreateDate(da);
	    	enquiryGoodsReply.setUpdateDate(da);
	    	if(rearks!=null  && rearks.length>0){
				if(rearks[i]!=null&&rearks[i]!=""){
					enquiryGoodsReply.setRemarks(rearks[i]);
				}else{
					enquiryGoodsReply.setRemarks(null);
				}
			}else{
				enquiryGoodsReply.setRemarks(null);
			}
	    	
	    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			enquiryGoodsReply.setReceiveTime(sdf.parse(receiveDate[i]));
			if(!"0".equals(images[i])&&!fileName[i].isEmpty()){
				enquiryGoodsReply.setPhotos(fileName[i]+";"+images[i]);
			}else{
				if(!"0".equals(images[i])){
					enquiryGoodsReply.setPhotos(images[i]);	
				}else{
					enquiryGoodsReply.setPhotos(fileName[i]);
				}
			}
			enquiryGoodsReplyService.save(enquiryGoodsReply);
			} catch (ParseException e) {
				logger.info("saveEnquiry",e);
			}
		}
	      Integer userLength=0;
		   for (EnquiryGoods enquiryGoods : list) {
			List<EnquiryGoodsReply> enquiry=enquiryGoodsReplyService.selectByenquiryGoodsId(enquiryGoods.getId());
			  if(enquiry.isEmpty()){
			  userLength=1;
			  break;
			  }else{
				userLength=0;	
			   }
		    }
		   
		   for (EnquiryGoods enquiryGoods : list) {
			    if(userLength>0){
			    	enquiryGoods.setId(enquiryGoods.getId());
			    	enquiryGoods.setStatus("2");
			    	enquiryGoodsService.upStatus(enquiryGoods);
			    }else{
			    	enquiryGoods.setId(enquiryGoods.getId());
			    	enquiryGoods.setStatus("3");
			    	enquiryGoodsService.upStatus(enquiryGoods);
			    }
		    }
	   return REDIRECT;
   }
	
}